﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Web.Framework;
using System.Web.UI.HtmlControls;
using Web.Framework.Translate;
using Web.Framework.Misc;
using System.Web.Caching;
using WebAppAuthAdmin.Code;
using AuthApi.Contracts;
using WebAppAuthAdmin.Code.Security;
using System.Text;

namespace WebAppAuthAdmin
{
    public partial class SiteMaster : BaseMasterPage
    {
        public override void PreLoad()
        {
            base.PreLoad();
            this.pnlMessages.CssClass = "pnlMessagesClass displayNone";
            this.txtMessages.Text = string.Empty;
            BuildMenu();
        }

        public override void SetContextPicker(string urlPicker)
        {
            iframeContextPicker.Attributes.Add("src", urlPicker);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (this.Page.User.Identity.IsAuthenticated)
                {
                    Label loginName = (Label)this.HeadLoginView.FindControl("lblLoginName");
                    loginName.Text = BaseWebPage.DisplayUserName;
                }

                ValidarContextoConPermisos();
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            ForzarCargaDeContexto();
        }

        private void ForzarCargaDeContexto()
        {
            bool forzarSelección = false;
            Company company = AppContext.Instance.GetSingleCompanyContext(this.Context);
            if (company == null || company == CompanySinSeleccionar.Instance)
            {
                //company = CompanySinSeleccionar.Instance;
                forzarSelección = true;
                // Forzar la selección
            }

            if (forzarSelección)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "forzarContexto", "<script type='text/javascript'> window.forcePicker = true; </script>");
            }
        }

        private void ValidarContextoConPermisos()
        {
            List<Company> companyList = AppContext.Instance.GetCompanyContext(this.Context);
            // Valido los permisos

            bool algunoCambio = false;

            List<Company> companiesToRemove = new List<Company>();
            foreach (var company in companyList)
            {
                if (company.Id != CompanyIndependiente.Instance.Id)
                {
                    if (!HasPermissionFor(AppSecurity.APP_VIEW_COMPANY_ID_ + company.Id.ToString()))
                    {
                        algunoCambio = true;
                        companiesToRemove.Add(company);
                    }
                }
            }

            foreach (var company in companiesToRemove)
            {
                companyList.Remove(company);
            }

            if (algunoCambio)
            {
                AppContext.Instance.SetCompanyContext(this.Context, companyList);
            }

            MostrarCompaniasEnContexto(companyList);
        }

        private void MostrarCompaniasEnContexto(List<Company> companyList)
        {
            Control ctrlBienvenido = this.HeadLoginView.FindControl("lblPtoVtaBienvenido");
            if (ctrlBienvenido != null)
            {
                Label lblBienvendioPtoVta = (Label)ctrlBienvenido;

                StringBuilder builder = new StringBuilder();
                string separador = string.Empty;
                foreach (var company in companyList)
                {
                    builder.Append(separador);
                    builder.Append(company.Name);
                    separador = ", ";
                }

                lblBienvendioPtoVta.Text = builder.ToString();

                if (String.IsNullOrEmpty(lblBienvendioPtoVta.Text))
                {
                    lblBienvendioPtoVta.Text = "Sin marcas seleccionadas";
                }
            }
        }

        public override void ShowMessage(string message, WebMessageType type)
        {
            ShowMessage("Mensaje", message, type);
        }

        public override void ShowMessage(string title, string message, WebMessageType type)
        {
            this.pnlMessages.CssClass = "pnlMessagesClass displayBlock";
            this.txtErrorTitle.Text = title;
            this.txtMessages.Text = message;
            if (type != WebMessageType.Error)
            {
                pnlError.CssClass = "errorPanelMessage";
            }
            else
            {
                pnlError.CssClass = "errorPanelError";
            }
        }

        public override void MakeMenuVisible(bool visible)
        {
            this.NavigationMenu.Visible = visible;
            fl_menu_cmd.Visible = visible;
            pnlContextPicker.Visible = visible;
        }

        public override void LoadContextActions(List<LinkButton> linkButtons)
        {
            //<a href="#" class="menu_item_cmd">Crear Lista de Distribución</a>
            foreach (LinkButton lnkCtrl in linkButtons)
            {
                if (lnkCtrl.CssClass == null)
                {
                    lnkCtrl.CssClass = string.Empty;
                }

                lnkCtrl.CssClass = lnkCtrl.CssClass + " menu_item_cmd";
                this.pnlActionsMenu.Controls.Add(lnkCtrl);
            }
        }

        public override void BuildMenu()
        {
            List<WebApplicationInfo> applications = BasePage.GetApplications();
            List<Company> companies = BasePage.GetCompanies();

            //bool hasPermissionForCompany = true;

            //var contextCompany = AppContext.Instance.GetSingleCompanyContext(HttpContext.Current);
            //if (contextCompany != null)
            //{
            //    hasPermissionForCompany = HasPermissionFor(AppSecurity.APP_VIEW_COMPANY_ID_ + contextCompany.Id);
            //}

            fl_menu_cmd.Visible = this.NavigationMenu.Visible;

            if (this.NavigationMenu.Visible)
            {
                if (HasPermissionFor(AppSecurity.APP_VIEW_ALL_USERS))
                {
                    MenuItem ListaDeUsuariosCompletaMenu = new MenuItem()
                    {
                        NavigateUrl = "~/App/UserList.aspx",
                        Text = "Usuarios"
                    };

                    this.NavigationMenu.Items.Add(ListaDeUsuariosCompletaMenu);
                }

                MenuItem applicacionesMenu = new MenuItem()
                {
                    NavigateUrl = "~/App/ApplicationList.aspx", // permite ver las aplicaciones, luego la seguridad esta dada por la grilla de la pantalla
                    Text = "Aplicaciones"
                };

                this.NavigationMenu.Items.Add(applicacionesMenu);

                var companyContext = AppContext.Instance.GetSingleCompanyContext(this.Context);
                if (companyContext != null && companyContext.Id == 0)
                {
                    applications = applications.Where(a => a.RequiereLoginSinEmpresa).ToList();
                }
                else
                {
                    applications = applications.Where(a => !a.RequiereLoginSinEmpresa).ToList();
                }

                foreach (WebApplicationInfo appInfo in applications)
                {
                    if (companyContext != null && ((!appInfo.RequiereLoginSinEmpresa && companyContext.Id != 0) || (appInfo.RequiereLoginSinEmpresa && companyContext.Id == 0)))
                    {
                        if (HasPermissionFor(AppSecurity.APP_VIEW_ID_ + appInfo.Id.ToString()))
                        {
                            MenuItem appMenu = new MenuItem()
                            {
                                NavigateUrl = string.Format("~/App/ApplicationEdit.aspx?Id={0}", appInfo.Id),
                                Text = appInfo.Name
                            };

                            applicacionesMenu.ChildItems.Add(appMenu);

                            if (HasPermissionFor(AppSecurity.APP_VIEW_USERS_ID_ + appInfo.Id.ToString()))
                            {
                                MenuItem userByAppMenu = new MenuItem()
                                {
                                    NavigateUrl = string.Format("~/App/UserList.aspx?applicationId={0}", appInfo.Id),
                                    Text = "Ver Usuarios de " + appInfo.Name
                                };

                                appMenu.ChildItems.Add(userByAppMenu);
                            }

                            if (HasPermissionFor(AppSecurity.APP_USER_CREATE + appInfo.Id.ToString()))
                            {
                                MenuItem createUserByAppMenu = new MenuItem()
                                {
                                    NavigateUrl = string.Format("/App/UserCreate.aspx?applicationId={0}", appInfo.Id),
                                    Text = "Crear usuario para " + appInfo.Name
                                };

                                appMenu.ChildItems.Add(createUserByAppMenu);
                            }
                        }
                    }
                }

                MenuItem companiesMenu = new MenuItem()
                {
                    NavigateUrl = "~/App/CompanyList.aspx",
                    Text = "Marcas"
                };

                this.NavigationMenu.Items.Add(companiesMenu);

                MenuItem changePasswordMenu = new MenuItem()
                {
                    NavigateUrl = "~/App/CambiarPassword.aspx",
                    Text = "Cambiar Mi Password"
                };

                this.NavigationMenu.Items.Add(changePasswordMenu);

                foreach (Company company in companies)
                {
                    if (HasPermissionFor(AppSecurity.APP_VIEW_COMPANY_ID_ + company.Id.ToString()))
                    {
                        MenuItem companyMenu = new MenuItem()
                        {
                            NavigateUrl = string.Format("~/App/CompanyEdit.aspx?Id={0}", company.Id),
                            Text = company.Name
                        };

                        companiesMenu.ChildItems.Add(companyMenu);
                    }
                }

            }
        }
    }
}
